package com.supor.aiot.mine.ui.feedback;


import android.Manifest;
import android.annotation.SuppressLint;
import android.content.Intent;
import android.text.Editable;
import android.text.InputFilter;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.MotionEvent;
import android.view.View;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.android.baseconfig.base.BaseSharedPreferences;
import com.android.baseconfig.common.callback.OnItemClickListener;
import com.android.baseconfig.common.helper.PermissionsChecker;
import com.android.baseconfig.common.rxpermissions2.RxPermissions;
import com.android.baseconfig.common.utils.Logc;
import com.android.baseconfig.common.utils.ToastUtils;
import com.android.baseconfig.common.views.AppBasicDialog;
import com.supor.aiot.common.app.AppAgent;
import com.supor.aiot.common.app.Constants;
import com.supor.aiot.common.app.SuporPresenter;
import com.supor.aiot.common.arouter.PathUrl;
import com.supor.aiot.common.base.BaseConfigActivity;
import com.supor.aiot.common.base.NoViewModel;
import com.supor.aiot.common.entity.FeedbackBean;
import com.supor.aiot.common.entity.QuestionTypeBean;
import com.supor.aiot.common.entity.UploadResultBean;
import com.supor.aiot.common.helper.ActivityHelper;
import com.supor.aiot.common.helper.GridItemDecoration;
import com.supor.aiot.mine.R;
import com.supor.aiot.mine.bean.ImageItem;
import com.supor.aiot.mine.databinding.ActivityFeedbackBinding;
import com.supor.aiot.mine.helper.FeedbackImageCache;
import com.supor.aiot.mine.ui.adapter.UploadImageAdapter;
import com.supor.aiot.mine.utils.FeedbackPop;

import java.util.ArrayList;
import java.util.List;

import androidx.annotation.Nullable;
import androidx.core.content.ContextCompat;
import androidx.recyclerview.widget.GridLayoutManager;

/**
 * ---------------------------------------------------------------- <br>
 * Copyright (C) 2014-2020, by het, Shenzhen, All rights reserved.  <br>
 * ---------------------------------------------------------------- <br>
 * <p>
 * 描述: 反馈页面 <br>
 * 作者: lei <br>
 * 日期: 2021/2/1 <br>
 */
@Route(path = PathUrl.PATH_FEEDBACK)
public class FeedbackActivity extends BaseConfigActivity<NoViewModel, ActivityFeedbackBinding>
        implements FeedbackPresenter.FeedbackView, FeedbackPop.FeedbackCallback {

    private UploadImageAdapter uploadImageAdapter;
    private List<ImageItem> itemList = new ArrayList<>();
    private FeedbackPresenter presenter;
    private RxPermissions rxPermissions;
    private int photoPosition = 0;
    private int questionPosition = 0;
    private ArrayList<String> questionList = new ArrayList<>();
    List<QuestionTypeBean> questionTypeBeanList;
    private AppBasicDialog commonDialog;
    int itemPosition;

    @Override
    protected int resourceId() {
        return R.layout.activity_feedback;
    }

    @Override
    protected void initView() {
        super.initView();
        bindingView.setViewM(this);
        initSceneRecyclerView();
    }

    @Override
    protected void initData() {
        super.initData();
        rxPermissions = new RxPermissions(this);
        presenter = new FeedbackPresenter(this, this);
        // presenter.getQuestionType();
        bindingView.toolbar.setIvLeftOnClickListener(v -> finish());
        bindingView.toolbar.setTvLeftOnClickListener(v -> finish());
        bindingView.feedback.setFilters(new InputFilter[]{new InputFilter.LengthFilter(500)});
        bindingView.feedback.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
            }

            @Override
            public void afterTextChanged(Editable s) {
                checkBtnState();
            }
        });
        bindingView.feedback.setOnTouchListener((v, event) -> {
            /*告诉父组件不要拦截他的触摸事件*/
            v.getParent().requestDisallowInterceptTouchEvent(true);
            if (MotionEvent.ACTION_UP == event.getAction()) {
                /*告诉父组件可以拦截他的触摸事件*/
                v.getParent().requestDisallowInterceptTouchEvent(false);
            }
            return false;
        });

        FeedbackPop.getInstance().init(this, this);
    }

    private void initSceneRecyclerView() {
        FeedbackImageCache.getInstance().cleanBimp();
        // 设置布局管理器
        GridLayoutManager gridLayoutManager = new GridLayoutManager(this, 3);
        bindingView.rcvPhoto.setLayoutManager(gridLayoutManager);
        bindingView.rcvPhoto.addItemDecoration(new GridItemDecoration(ContextCompat.getColor(this,
                R.color.transparent), getResources().getDimensionPixelSize(R.dimen.dp_4),
                getResources().getDimensionPixelSize(R.dimen.dp_6), -1));
        // 设置适配器
        itemList.add(new ImageItem(Constants.ADD_PHOTO));
        itemList.add(new ImageItem(Constants.ADD_VIDEO));
        uploadImageAdapter = new UploadImageAdapter(this, itemList);
        uploadImageAdapter.setItemClickListener(new OnItemClickListener() {
            @SuppressLint("CheckResult")
            @Override
            public void onItemClick(View view, int position) {
                itemPosition = position;
                rxPermissions.request(Manifest.permission.WRITE_EXTERNAL_STORAGE)
                        .subscribe(aBoolean -> {
                            if (aBoolean) {
                                itemClick(view, position);
                            } else {
                                Logc.i("permission request: failed");
                                showDialog();
                            }
                        });
            }

            @Override
            public boolean onItemLongClick(View view, int position) {
                return false;
            }
        });
        bindingView.rcvPhoto.setAdapter(uploadImageAdapter);
    }

    @Override
    protected boolean isUseBlackFontWithStatusBar() {
        return true;
    }

    @Override
    public void onResume() {
        super.onResume();
        checkBtnState();
    }

    private void checkBtnState() {
        if (TextUtils.isEmpty(bindingView.feedback.getInputText().trim())) {
            bindingView.btnSave.setEnabled(false);
        } else {
            bindingView.btnSave.setEnabled(true);
        }
        bindingView.tvCount.setText((bindingView.feedback.getInputText().trim().length() + "/500"));
    }

    /**
     * 显示缺失权限提示
     */
    protected void showDialog() {
        if (commonDialog != null && commonDialog.isShowing()) {
            commonDialog.dismiss();
        }
        AppBasicDialog.Builder builder = new AppBasicDialog.Builder(this, false);
        builder.setTitle(R.string.permission_storage_title);
        builder.setMessage(R.string.permission_storage_msg);
        builder.setNegativeButton(R.string.cancel, (dialog, which) -> dialog.dismiss());
        builder.setPositiveButton(R.string.go_settings, (dialog, which) -> {
            ActivityHelper.startAppSettings(FeedbackActivity.this, Constants.REQUEST_CODE2);
            dialog.dismiss();
        });
        commonDialog = builder.create();
        commonDialog.setCancelable(false);
        commonDialog.show();
    }

    public void onViewClicked(View view) {
        int id = view.getId();
        if (id == R.id.btn_save) {
            // if (TextUtils.isEmpty(bindingView.tvSelectQuestion.getText())) {
            //     ToastUtils.getInstance().showCustomToast(R.string.feedback_question_type_tip);
            //     return;
            // }
            if (TextUtils.isEmpty(bindingView.feedback.getText())) {
                ToastUtils.getInstance().showCustomToast(R.string.feedback_question_desc_tip);
                return;
            }
            if (FeedbackImageCache.getInstance().fileOverSize(itemList)) {
                ToastUtils.getInstance().showCustomToast("单个文件请不要超过50M");
                return;
            }
            List<String> photoPaths = new ArrayList<>();
            for (int i = 0; i < itemList.size() - 2; i++) {
                photoPaths.add(itemList.get(i).imagePath);
            }
            if (!Constants.ADD_VIDEO.equalsIgnoreCase(itemList.get(itemList.size() - 1).imagePath)) {
                photoPaths.add(itemList.get(itemList.size() - 1).imagePath);
            }
            if (!Constants.ADD_PHOTO.equalsIgnoreCase(itemList.get(itemList.size() - 2).imagePath)) {
                photoPaths.add(itemList.get(itemList.size() - 2).imagePath);
            }
            if (photoPaths.size() > 0) {
                presenter.uploadFeedbackImage(photoPaths);
            } else {
                FeedbackBean feedbackBean = new FeedbackBean();
                feedbackBean.setFbContent(bindingView.feedback.getText().toString());
                feedbackBean.setFbTime(String.valueOf(System.currentTimeMillis()));
                feedbackBean.setQuestionType("03");
                presenter.feedback(feedbackBean);
            }
        } else if (id == R.id.tv_select_question || id == R.id.iv_right_arrow) {
            if (questionList.size() == 0) {
                ToastUtils.getInstance().showCustomToast(R.string.feedback_no_question);
                return;
            }
            FeedbackPop.getInstance().showQuestionPop(this, bindingView.llRoot);
        } else if (id == R.id.tv_ips_des) {

        }
    }

    private void itemClick(View view, int position) {
        this.photoPosition = position;
        if (view != null) {
            if (view.getId() == R.id.iv_del) {
                itemList.remove(photoPosition);
                uploadImageAdapter.notifyItemRemoved(photoPosition);

                if (position == itemList.size()) {
                    itemList.add(itemList.size(), new ImageItem(Constants.ADD_VIDEO));
                    uploadImageAdapter.notifyItemInserted(itemList.size() - 1);
                } else if (position == itemList.size() - 1) {
                    itemList.add(itemList.size() - 1, new ImageItem(Constants.ADD_PHOTO));
                    uploadImageAdapter.notifyItemInserted(itemList.size() - 2);
                } else {
                    if (!Constants.ADD_PHOTO.equalsIgnoreCase(itemList.get(itemList.size() - 2).imagePath)) {
                        itemList.add(itemList.size() - 1, new ImageItem(Constants.ADD_PHOTO));
                        uploadImageAdapter.notifyItemInserted(itemList.size() - 2);
                    }
                }
            } else {
                if (position == itemList.size() - 2) {
                    if (Constants.ADD_PHOTO.equalsIgnoreCase(itemList.get(itemList.size() - 2).imagePath)) {
                        FeedbackImageCache.getInstance().cleanBimp();
                        if (itemList.size() > 2) {
                            for (int i = 0; i < itemList.size() - 2; i++) {
                                FeedbackImageCache.getInstance().getDrr().add(itemList.get(i).imagePath);
                                FeedbackImageCache.getInstance().getSelectItem().add(itemList.get(i));
                            }
                        }

                        Intent intent = new Intent(this, ImageGridActivity.class);
                        // max number
                        intent.putExtra(Constants.Key.NUM, 9);
                        // type 0-photo|1-video
                        intent.putExtra(Constants.Key.param_type, 0);
                        startActivityForResult(intent, Constants.REQUEST_CODE);
                    }
                } else if (position == itemList.size() - 1) {
                    if (Constants.ADD_VIDEO.equalsIgnoreCase(itemList.get(itemList.size() - 1).imagePath)) {
                        FeedbackImageCache.getInstance().cleanBimp();
                        Intent intent = new Intent(this, ImageGridActivity.class);
                        intent.putExtra(Constants.Key.NUM, 1);
                        // type 0-photo|1-video
                        intent.putExtra(Constants.Key.param_type, 1);
                        startActivityForResult(intent, Constants.REQUEST_CODE);
                    }
                }
            }
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == Constants.REQUEST_CODE) {
            if (resultCode == 0) {
                if (!Constants.ADD_PHOTO.equals(itemList.get(itemList.size() - 2).imagePath)) {
                    return;
                }
                if (FeedbackImageCache.getInstance().getDrr().size() > 0) {
                    // itemList.clear();
                    List<String> paths = FeedbackImageCache.getInstance().getDrr();
                    int len = paths.size();
                    int itemSize = itemList.size() - 2;
                    if (len > itemSize) {
                        ImageItem videoItem = itemList.remove(itemSize + 1);
                        itemList.remove(itemSize);
                        for (int i = itemSize; i < len; i++) {
                            itemList.add(FeedbackImageCache.getInstance().getSelectItem().get(i));
                        }
                        if (len != 9) {
                            itemList.add(new ImageItem(Constants.ADD_PHOTO));
                            itemList.add(videoItem);
                            uploadImageAdapter.notifyItemRangeChanged(itemSize, len - itemSize + 2);
                        } else {
                            itemList.add(videoItem);
                            uploadImageAdapter.notifyItemRangeChanged(itemSize, len - itemSize);
                        }
                    }
                }

            }
            if (resultCode == 1) {
                if (!Constants.ADD_VIDEO.equals(itemList.get(itemList.size() - 1).imagePath)) {
                    return;
                }
                if (FeedbackImageCache.getInstance().getDrr().size() > 0) {
                    // itemList.clear();
                    List<String> paths = FeedbackImageCache.getInstance().getDrr();
                    int len = paths.size();
                    if (len != 1) {
                        return;
                    }
                    itemList.remove(itemList.size() - 1);
                    itemList.add(FeedbackImageCache.getInstance().getSelectItem().get(0));
                    uploadImageAdapter.notifyItemChanged(itemList.size() - 1);
                }
            }
        } else if (requestCode == Constants.REQUEST_CODE2) {
            PermissionsChecker mPermissionsChecker = new PermissionsChecker(this);
            if (!mPermissionsChecker.lacksPermissions(Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
                Logc.i("permission request: success");
                // itemClick(view, itemPosition);
            }
        }
    }

    @Override
    public void onPreview() {
        final Intent intent = new Intent(FeedbackActivity.this, PhotoActivity.class);
        intent.putExtra(Constants.Key.ID, photoPosition);
        startActivity(intent);
    }

    @Override
    public void onDelete() {
        FeedbackImageCache.getInstance().getDrr().remove(photoPosition);
        itemList.remove(photoPosition);
        uploadImageAdapter.notifyItemRemoved(photoPosition);
        if (!Constants.ADD.equals(itemList.get(itemList.size() - 1).imagePath)) {
            itemList.add(new ImageItem(Constants.ADD));
            uploadImageAdapter.notifyItemInserted(itemList.size() - 1);
        }
    }

    @Override
    public void questionType(List<QuestionTypeBean> list) {
        questionTypeBeanList = list;
        questionList.clear();
        for (QuestionTypeBean questionTypeBean : list) {
            questionList.add(questionTypeBean.getCnName());
        }
        FeedbackPop.getInstance().setDataList(questionList);
    }

    @Override
    public void uploadFileSuccess(List<UploadResultBean> uploadResultBeanList) {
        FeedbackBean feedbackBean = new FeedbackBean();
        feedbackBean.setFbContent(bindingView.feedback.getText().toString());
        feedbackBean.setFbTime(String.valueOf(System.currentTimeMillis()));
        feedbackBean.setBoosTFeedbackImages(uploadResultBeanList);
        feedbackBean.setQuestionType("03");
        presenter.feedback(feedbackBean);
    }

    @Override
    public void uploadFileFailed(String reason) {
        showDialog("", reason, getString(R.string.i_know), (dialog, which) -> dialog.dismiss());
    }

    @Override
    public void feedbackFailed(int status, String reason) {
        if (status == 1009) {
            BaseSharedPreferences.setString(AppAgent.getApp(),
                    Constants.Key.param_saveInfo, "");
            ToastUtils.getInstance().showCustomToast(R.string.user_close_account);
            SuporPresenter.getInstance().reportCloseAccount(1);
            finish();
            return;
        }
        showDialog("提示", reason, getString(R.string.i_know), (dialog, which) -> dialog.dismiss());
    }

    @Override
    public void onQuestionTypeItem(int position) {
        questionPosition = position;
        String questionName = questionList.get(position);
        if ("产品连网问题".equalsIgnoreCase(questionName)) {
            bindingView.feedback.setHint(R.string.feedback_input_hint_config);
        } else {
            bindingView.feedback.setHint(R.string.feedback_input_hint);
        }
        bindingView.tvSelectQuestion.setText(questionName);
    }

    @Override
    public void showToast(String data) {

    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        FeedbackImageCache.getInstance().cleanBimp();
    }
}

